package com.zhang.boot.core.security;

import cn.hutool.json.JSONUtil;
import com.zhang.boot.core.constants.HttpStatus;
import com.zhang.boot.core.util.ServletUtils;
import com.zhang.boot.core.vo.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * 认证失败处理类,返回未授权
 */
@Component
public class UnAuthorizedHandler implements AuthenticationEntryPoint, Serializable {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        int code = HttpStatus.UNAUTHORIZED;

        String msg = String.format("请求访问:%s,认证失败,无法访问系统资源", httpServletRequest.getPathInfo());
        ServletUtils.renderString(httpServletResponse, JSONUtil.toJsonStr(new Result<>(code, msg)));
    }
}
